package cn.tx.trans;

import cn.tx.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Demo {

    public static void trans() throws SQLException {
        String sql="update account t set t.balance=t.balance-10000 where t.ID=1";
        String sql1="update account t set t.balance=t.balance+10000 where t.ID=2";

        PreparedStatement ps= DBUtil.getPrepareStatement(sql);
        PreparedStatement ps1=DBUtil.getPrepareStatement(sql1);
        ps.executeUpdate();
        int i=1/0;
        ps1.executeUpdate();

        DBUtil.closeRes(ps);
        DBUtil.closeRes(ps1);



    }
    public static void trans1(){
        String sql="update account t set t.balance=t.balance-10000 where t.ID=1";
        String sql1="update account t set t.balance=t.balance+10000 where t.ID=2";

        Connection conn = DBUtil.getConn();
        PreparedStatement statement = null;
        PreparedStatement statement1= null;
        try {
            conn.setAutoCommit(false);


            statement = conn.prepareStatement(sql);
            statement1 = conn.prepareStatement(sql1);

            statement.executeUpdate();
            //int i=1/0;
            statement1.executeUpdate();

            //手动提交
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

        } finally {
            DBUtil.closeRes(statement);
            DBUtil.closeRes(statement1);
            //事务回滚

        }

    }

    public static void main(String[] args) throws SQLException {
        trans1();
    }
}
